/***
 * @description 商品修改示例代码
 *    新增页：http://localhost:3000/#/product-update
 *    修改页：http://localhost:3000/#/product-update?productId=1
 * @author Zhang Guimei
 */
import {
  Bar,
  Button,
  Col,
  DatePicker,
  FormLabel,
  Input,
  Radio,
  Row,
  Select
} from '@casstime/bricks';
import { observer } from 'mobx-react';
import React from 'react';
import { RouteConfigComponentProps } from 'react-router-config';

import Page from '../../../components/Page';
import { parseLocationSearch } from '../../../utils';

import ProductUpdateStore from '../stores/ProductUpdateStore';
import CategoryModal from './CategoryModal';

export interface IHomePageProps extends RouteConfigComponentProps<void> {
  productUpdateStore: ProductUpdateStore;
}

const PRODUCT_TYPE = [
  {
    value: 'SINGLE',
    label: '单品'
  },
  {
    value: 'SUIT',
    label: '套装'
  }
];

@observer
class Main extends React.Component<IHomePageProps, {}> {
  public productId?: string;

  private getProductIdFromQuery() {
    const query = parseLocationSearch(this.props.location.search);
    return query.productId as (string | undefined);
  }

  componentDidMount() {
    const productUpdateStore = this.props.productUpdateStore;
    const productId = this.getProductIdFromQuery();
    if (productId) {
      productUpdateStore.getProductDetail(productId);
    }
    productUpdateStore.getQualityList();
    productUpdateStore.getAreaList();
    productUpdateStore.getCategoryList();
  }

  render() {
    const { productUpdateStore } = this.props;
    const { productDetail, qualityList } = productUpdateStore;
    return (
      <Page title="主页" className="product-update-page">
        <Bar onGoBack={this.goBack} showGoBackButton>
          商品修改
        </Bar>
        {this.renderRow(
          this.renderLabel('商品名称'),
          <Col sm={5}>
            <Input
              type="text"
              value={productDetail.productName || ''}
              onChange={e => productUpdateStore.changeProductName(e)}
              maxLength={20}
              placeholder="请自定义名称，20个字以内"
            />
          </Col>
        )}

        {this.renderRow(
          this.renderLabel('商品类型'),
          <Col sm={5}>
            {PRODUCT_TYPE.map(productType => {
              return (
                <Radio
                  key={productType.value}
                  name={productType.label}
                  checked={productType.value === productDetail.productType}
                  onChange={value =>
                    productUpdateStore.changeProductType(value)
                  }
                  value={productType.value}
                />
              );
            })}
          </Col>
        )}

        {this.renderRow(
          this.renderLabel('商品品质'),
          <Col sm={5}>
            <Select
              value={productDetail.productQuality || { value: '', label: '' }}
              onChange={option =>
                productUpdateStore.changeProductQuality(option)
              }
              options={qualityList}
            />
          </Col>
        )}

        {this.renderRow(
          this.renderLabel('商品品类'),
          <Col sm={5}>
            <Input
              className="category-input"
              value={(productDetail.productCategory || [])
                .map(v => v.title || '')
                .join(',')}
              onFocus={() => productUpdateStore.toggleCategotyModal(true)}
            />
          </Col>
        )}

        {this.renderRow(this.renderLabel('商品描述'), [
          <Col sm={4} key="start-time">
            <DatePicker
              className="start-time"
              onChange={value =>
                productUpdateStore.changeProductDate(value, 'startTimeMoment')
              }
              value={productDetail.startTimeMoment}
            />
          </Col>,
          <Col sm={4} key="end-time">
            <DatePicker
              className="end-time"
              onChange={value =>
                productUpdateStore.changeProductDate(value, 'endDateMoment')
              }
              value={productDetail.endDateMoment}
            />
          </Col>
        ])}

        {this.renderRow(
          this.renderLabel('商品描述'),
          <Col sm={8}>
            <div className="product-detail-wrapper">
              <textarea
                className="product-detail"
                value={productDetail.productDesc}
                placeholder="请填写商品描述"
                onChange={value =>
                  productUpdateStore.changeProductDetail(value)
                }
              />
              <span className="limit-length">
                <span className="product-detail-length">
                  {productDetail.productDesc
                    ? productDetail.productDesc.length
                    : 0}
                </span>
                /200
              </span>
            </div>
          </Col>
        )}

        <Button
          className="save-btn"
          onClick={productUpdateStore.saveProductInfo}
        >
          保存
        </Button>

        {productUpdateStore.showCategoryModal && (
          <CategoryModal
            categoryList={productUpdateStore.categoryList}
            checkedData={productDetail.productCategory}
            {...this.props}
            hideModal={() => productUpdateStore.toggleCategotyModal(false)}
            submit={data => productUpdateStore.changeCategoryData(data)}
          />
        )}
      </Page>
    );
  }

  /**
   * 渲染一行表单
   * @param label 表单标签
   * @param value 表单
   */
  renderRow = (label: React.ReactNode, value: React.ReactNode) => {
    return (
      <Row>
        {label}
        {value}
      </Row>
    );
  };

  /**
   * 渲染表单label
   * @param title 表单标题
   */
  renderLabel = (title: string | React.ReactNode) => {
    return (
      <Col sm={1} className="align-right label-wrapper">
        <FormLabel align="right">
          <span className="required">{title}：</span>
        </FormLabel>
      </Col>
    );
  };

  /**
   * 返回
   */
  goBack = () => {
    const { history } = this.props;
    history.goBack();
  };
}

export default Main;
